package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Product;
import cn.wolfcode.trip.base.domain.ProductContent;
import cn.wolfcode.trip.base.mapper.ProductContentMapper;
import cn.wolfcode.trip.base.mapper.ProductMapper;
import cn.wolfcode.trip.base.query.ProductQueryObject;
import cn.wolfcode.trip.base.service.IProductService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author by mycp
 * @Classname ProductServiceImpl
 * @Description TODO
 * @Date 2018/11/14 18:24
 */
@Service
public class ProductServiceImpl implements IProductService {
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductContentMapper productContentMapper;

    @Override
    public PageInfo query(ProductQueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Product> list = productMapper.selectForList(qo);
        return new PageInfo(list);
    }

    @Override
    public void saveOrUpdate(Product product) {
        // 判断积分商品是否有排序, 如果没有, 需要手动设置
        if (product.getSequence() == null){
            // 先查询出商品分类对应的积分商品最大的排序
            Integer sequence = productMapper.
                    selectSequenceByProductCatalogId(product.getProductcatalogId());
            if (sequence == null) {
                sequence = 0;
            }

            // 设置当前商品的最大排序为最大值 +1
            product.setSequence(sequence + 1L);
        }

        // 判断新增积分商品 / 修改
        if (product.getId() == null){
            // 保存商品信息
            productMapper.insert(product);

            // 设置主键关联
            ProductContent content = product.getContent();
            content.setId(product.getId());
            productContentMapper.insert(content);
        } else {
            // 先更新文章
            productMapper.updateByPrimaryKey(product);
            ProductContent content = product.getContent();
            content.setId(product.getId());
            productContentMapper.update(content);
        }

    }

    @Override
    public ProductContent getContentById(Long id) {
        return productContentMapper.getContentByProductId(id);
    }

    @Override
    public Product getProductById(Long productId) {
        return productMapper.selectByPrimaryKey(productId);
    }

    @Override
    public List<Product> getProductsByCatalogId(Long catalogId) {
        return productMapper.getProductsByCatalogId(catalogId);
    }
}
